package com.yangziqiang.controller;


import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.carrey.common_utils.SnowflakeIdWorker;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.yangziqiang.common.MsgResult;
import com.yangziqiang.entity.EsMovies;
import com.yangziqiang.entity.Movies;
import com.yangziqiang.entity.QueryVo;
import com.yangziqiang.mapper.MoviesRepository;
import com.yangziqiang.service.IMoviesService;
import com.yangziqiang.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.aggregation.AggregatedPage;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author BenjaminYang
 * @since 2022-02-09
 */
@RestController
@RequestMapping("/movies")
public class MoviesController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    MoviesRepository mmoviesRepository;

    @Autowired
    IMoviesService iMoviesService;

    @Autowired
    KafkaTemplate kafkaTemplate;

    @Autowired
    ElasticsearchTemplate elasticsearchTemplate;

    @GetMapping("esList")
    public MsgResult esList(QueryVo qv, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "2") Integer pageSize) {
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if (mmoviesRepository.count() < 1) {
            List<EsMovies> list = iMoviesService.listForEs();
            mmoviesRepository.saveAll(list);
        }
        if (StringUtils.isNotBlank(qv.getQname())) {
            boolQuery.must(QueryBuilders.matchQuery("mname", qv.getQname()));
        }
        if (StringUtils.isNotBlank(qv.getQdirector())) {
            boolQuery.must(QueryBuilders.matchQuery("director", qv.getQdirector()));
        }
        if (StringUtils.isNotBlank(qv.getQcheckStatus())) {
            boolQuery.must(QueryBuilders.matchPhraseQuery("checkStatus", qv.getQcheckStatus()));
        }
        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder()
                .withQuery(boolQuery)
                .withPageable(PageRequest.of(pageNum - 1, pageSize));
        AggregatedPage<EsMovies> movies = elasticsearchTemplate.queryForPage(nativeSearchQueryBuilder.build(), EsMovies.class);
        Page<EsMovies> page = new Page<>(pageNum, pageSize);
        page.setTotal(movies.getTotalElements());
        PageInfo<EsMovies> pg = new PageInfo<>(page);
        pg.setList(movies.getContent());
        return MsgResult.succeed(pg);
    }

    @PostMapping("addMovies")
    public MsgResult addMovies(@RequestBody Movies movies) {
        if (StringUtils.isBlank(movies.getMname())) {
            return MsgResult.fail(300, "参数不能为空！", movies);
        }
        String requestURI = WebUtils.getRequest().getRequestURI();
        String params = JSON.toJSONString(movies);
        String token = SecureUtil.md5(requestURI + params);
        if (!redisTemplate.opsForValue().setIfAbsent(token, null, 10, TimeUnit.SECONDS)) {
            return MsgResult.fail(300, "请不要重复提交！！", movies);
        }
        boolean save = iMoviesService.save(movies);
        String orderId = SnowflakeIdWorker.getOrderId();
        kafkaTemplate.send("test111", "add:" + orderId, JSON.toJSONString(movies));
        redisTemplate.opsForValue().set("addMovies:add:" + orderId, JSON.toJSONString(movies));
        return MsgResult.succeed();
    }

    @PostMapping("updMovies")
    public MsgResult updMovies(@RequestBody Movies movies) {
        if (StringUtils.isBlank(movies.getMname())) {
            return MsgResult.fail(300, "参数不能为空！", movies);
        }
        String requestURI = WebUtils.getRequest().getRequestURI();
        String params = JSON.toJSONString(movies);
        String token = SecureUtil.md5(requestURI + params);
        if (!redisTemplate.opsForValue().setIfAbsent(token, null, 10, TimeUnit.SECONDS)) {
            return MsgResult.fail(300, "请不要重复提交！！", movies);
        }
        boolean save = iMoviesService.updateById(movies);
        String orderId = SnowflakeIdWorker.getOrderId();
        kafkaTemplate.send("test111", "upd:" + orderId, JSON.toJSONString(movies));
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("movieJson", JSON.toJSONString(movies));
        hashMap.put("movieTime", System.currentTimeMillis());
        redisTemplate.opsForHash().putAll("updMovies:upd:" + orderId, hashMap);
//        redisTemplate.opsForValue().set("updMovies:upd:" + orderId, JSON.toJSONString(movies));
        return MsgResult.succeed();
    }

    @PostMapping("changeStatus")
    public MsgResult changeStatus(@RequestBody Movies movies) {
        boolean save = iMoviesService.updateById(movies);
        String orderId = SnowflakeIdWorker.getOrderId();
        kafkaTemplate.send("test111", "cha:" + orderId, JSON.toJSONString(movies));
        redisTemplate.opsForValue().set("chaMovies:cha:" + orderId, JSON.toJSONString(movies));
        return MsgResult.succeed();
    }

    @PostMapping("delMovies")
    public MsgResult delMovies(@RequestBody Movies movies) {
        iMoviesService.removeById(movies.getMid());
        String orderId = SnowflakeIdWorker.getOrderId();
        kafkaTemplate.send("test111", "del:" + orderId, JSON.toJSONString(movies.getMid()));
        redisTemplate.opsForValue().set("delMovies:del:" + orderId, JSON.toJSONString(movies.getMid()));
        return MsgResult.succeed();
    }
}
